/**
 * 表单设置
 */
;
(function(global, factory) {
	"use strict";
	if(typeof define === "function" && define.amd) {
		define(['jquery', 'util/commonUtil', 'util/formElementManager', 'util/formValidator'], function(a, b, c) {
			return factory(global, a, b, c);
		});
	} else {
		factory(global);
	}
})(typeof window !== "undefined" ? window : this, function(window, $, commonUtil, formElementManager, formValidator) {

	/**
	 * 针对表单渲染设值面板
	 * @param {Object} dragElement
	 */
	let _001_renderPanel = function() {
		let activeElement = $("#layout-main .draggable-element.active");
		let tmpInstance = activeElement.data('componentInstance');
		let setli = $("#form-setting");
		setli.empty();
		if( activeElement && activeElement.length && tmpInstance ) {
			//console.log(tmpInstance);
			let settins = tmpInstance.formSets();
			//console.log(settins);
			for( let i in settins ) {
				let si = settins[i];
				si.render(setli, tmpInstance);//调用设置项上定义的渲染方法
			}
			//初始化自定义事件
			this.formEvent.render(activeElement, tmpInstance);
		} else {
			//setli.html('暂无设置项');
			let html = '<div style="text-align: center;">';
			html += '<span style="color: #cfe6fb;font-size: 100px;" class="glyphicon glyphicon-copy"></span><br>';
			html += '<span style="color: #333;font-size: 14px;">暂无设置项</span><br>';
			html += '</div>';
			setli.html(html);						
		}
	}
	
	/**
	 * 渲染布局设置
	 * @param {Object} layoutElement
	 */
	let _002_renderLayoutSettingPanel = function() {
		let activeElement = $("#layout-main .content-column.active");
		let setli = $("#form-setting");
		setli.empty();
		
		let renderer = function(layoutElement) {
			let html = '';
			let setli = $("#form-setting");
			setli.empty();
			{
				//设置内容DOM
				html += '<div class="form-group">';
				html += ' <label for="layoutSetting-title">标题</label>';
				html += ' <input type="text" class="form-control" id="layoutSetting-title">';
				html += '</div>';
				
				/**
				html += '<div class="form-group">';
				html += ' <label for="layoutSetting-width">布局宽度</label>';
				html += ' <select class="form-control" id="layoutSetting-width">';
				html += ' <option value="">默认</option>';
				html += ' <option value="6">50%</option>';
				html += ' </select>';
				html += '</div>';
				*/
				
				html += '<div class="form-group">';
				html += ' <label for="layoutSetting-innerWidth">内部元素宽度</label>';
				html += ' <select class="form-control" id="layoutSetting-innerWidth">';
				html += ' <option value="">默认</option>';
				html += ' <option value="6">50%</option>';
				html += ' </select>';
				html += '</div>';
				
				setli.append(html);
			}
			
			{
				//设置初始值
				$("#layoutSetting-title").val(getLabel());
				$("#layoutSetting-width").val(getWidth());
				$("#layoutSetting-innerWidth").val(getInnerWidth());
			}
			
			{
				//绑定事件
				$("#layoutSetting-title").on("input", function(){
					setLabel($(this).val());
				});
				$("#layoutSetting-width").on("change", function(){
					setWidth($(this).val());
				});
				$("#layoutSetting-innerWidth").on("change", function(){
					setInnerWidth($(this).val());
				});
			}
		}
		
		let getLabel = function() {
			return activeElement.find(".laytitle").html();
		}
		let setLabel = function(txt) {
			activeElement.find(".laytitle").text(txt);
		}
		
		let getWidth = function() {
			return activeElement.attr("data-laywidth") || "";
		}
		let setWidth = function(txt) {
			let preWidth = activeElement.attr("data-laywidth");
			if(preWidth) {
				activeElement.removeClass( "form-col-" + preWidth );
			}
			if(txt) {
				activeElement.attr("data-laywidth", txt);
				activeElement.addClass( "form-col-" + txt );
			} else {
				activeElement.removeAttr("data-laywidth");
			}
		}
		
		let getInnerWidth = function() {
			return activeElement.attr("data-laywidth-inner") || "";
		}
		let setInnerWidth = function(txt) {
			let preWidth = activeElement.attr("data-laywidth-inner");
			if(preWidth) {
				activeElement.removeClass( "form-col-" + preWidth );
			}
			
			if(txt) {
				activeElement.attr("data-laywidth-inner", txt);
			} else {
				activeElement.removeAttr("data-laywidth-inner");
			}
			activeElement.find(".draggable-element").each(function(){
				let ghost = $(this);
				let tmpInstance = ghost.data("componentInstance");
				if(tmpInstance) {
					tmpInstance.updateWidth(txt);
				}
			});
		}
		
		if( activeElement && activeElement.length ) {
			renderer(activeElement);
		} else {
			//setli.html('暂无设置项');
			let html = '<div style="text-align: center;">';
			html += '<span style="color: #cfe6fb;font-size: 100px;" class="glyphicon glyphicon-copy"></span><br>';
			html += '<span style="color: #333;font-size: 14px;">暂无设置项</span><br>';
			html += '</div>';
			setli.html(html);		
		}
		//隐藏事件设置面板
		this.formEvent.hide();
		
	}
	
	
	let labelName = {
		"labelName": {
			"name": "标签名称",
			"render": function(parent, elementInstance) {
				let html = '', 
				    inputId = 'formSetting-labelName',
				    inputItem;
				
				{
					//设置项DOM定义
					html += '<div class="form-group">';
					html += ' <label for="formSetting-labelName">标签名称</label>';
					html += ' <input type="text" class="form-control" id="' + inputId + '" placeholder="标签名称">';
					html += ' <p class="text-info">标签名称中可使用<code>&lt;br&gt;</code>换行</p>';
					html += '</div>';
					parent.append(html);
				}
				
				inputItem = $("#"+inputId);
				
				{
					//设置输入项的值
					inputItem.val(elementInstance.label());
				}
				
				{
					//绑定设置项事件
					inputItem.on('input', function(evt){
						var val = $(this).val();
						elementInstance.label(val);
					});
				}
				
			}
		}
	}
	
	let defaultValue = {
		"defaultValue": {
			"name": "默认值",
			"render": function(parent, elementInstance) {
				let html = '', 
				    defaultValueInputDom = elementInstance.dom4SetDefaultValue(); //设置默认值的输入项，此方法触发事件绑定
				if(!defaultValueInputDom) {
					//组件不支持设置默认值
					return ;
				}
				
				{
					//设置项DOM定义
					html += '<div class="form-group">';
					html += ' <label for="formSetting-defaultValue">默认值</label>';
					//html += ' <input type="text" class="form-control" id="formSetting-defaultValue">';
					//html += defaultValueInputDom;
					html += '</div>';
					let tmpDom = $(html);
					tmpDom.append(defaultValueInputDom);
					parent.append(tmpDom);
				}
				
			}
		}
	}
	
	let formWidth = {
		"formWidth": {
			"name": "宽度",
			"render": function(parent, elementInstance) {
				let html = '', 
				    inputId = 'formSetting-width',
				    inputItem;
				
				{
					//设置项DOM定义
					html += '<div class="form-group">';
					html += ' <label for="formSetting-width">宽度</label><span class="text-warning"> (仅桌面端有效)</span>';
					html += ' <select class="form-control" id="formSetting-width">';
					html += ' <option value="">默认</option>';
					html += ' <option value="6">50%</option>';
					html += ' </select>';
					html += '</div>';
					parent.append(html);
				}
				
				inputItem = $("#"+inputId);
				
				{
					//设置输入项的值
					inputItem.val(elementInstance.getFormWidth());
				}
				
				{
					//绑定设置项事件
					inputItem.on('change', function(evt){
						var val = $(this).val();
						elementInstance.updateWidth(val);
					});
				}
			}
		}
	}
	
	let requireAndReadonly = {
		"requireAndReadonly": {
			"name": "必填、只读",
			"render": function(parent, elementInstance) {
				
				if(elementInstance.forceReadonly()) {
					return '';
				}
				
				let html = '',
				    inputId1 = 'formSetting-required',
				    inputId2 = 'formSetting-readonly',
				    inputItem1, 
				    inputItem2;
				
				{
					//设置项DOM定义
					html += '<div class="form-group">';
					html += ' <label class="checkbox-inline">';
					html += '  <input type="checkbox" id="formSetting-required" value="1"> 必填';
					html += ' </label>';
					html += ' <label class="checkbox-inline">';
					html += '  <input type="checkbox" id="formSetting-readonly" value="1"> 只读';
					html += ' </label>';
					html += '</div>';
					parent.append(html);
				}
				
				inputItem1 = $("#"+inputId1);
				inputItem2 = $("#"+inputId2);
				
				{
					//设置输入项的值
					let required = elementInstance.required();
					let readonly = elementInstance.readonly();
					inputItem1.prop("checked", required);
					inputItem2.prop("checked", readonly);
				}
				
				{
					//绑定设置项事件
					inputItem1.on('change', function(evt){
						var flag = $(this).prop("checked");
						elementInstance.required(flag);
						if(flag) {
							inputItem2.prop("checked", false).trigger("change");
						}
					});
					inputItem2.on('change', function(evt){
						var flag = $(this).prop("checked");
						elementInstance.readonly(flag);
						if(flag) {
							inputItem1.prop("checked", false).trigger("change");
						}
					});
				}
			}
		
		}
	}
	
	let prefix = {
		"prefix": {
			"name": "前缀",
			"render": function(parent, elementInstance) {
				let html = '', inputItem;
				{
					//设置项DOM定义
					html += '<div class="form-group">';
					html += ' <label for="formSetting-prefix">前缀</label>';
					html += ' <input type="text" class="form-control" id="formSetting-prefix">';
					html += '</div>';
					parent.append(html);
				}
				
				inputItem = $("#formSetting-prefix");
				
				{
					//设置输入项的值
					let val = elementInstance.prefix();
					if(val) {
						inputItem.val(val);
					}
				}
				
				{
					//绑定设置项事件
					inputItem.on('input', function(evt){
						var val = $(this).val();
						elementInstance.prefix(val);
					});
					
				}
			}
		}
	}
	
	let suffix = {
		"suffix": {
			"name": "后缀",
			"templete": function() {
				let html = '';
				//设置项DOM定义
				html += '<div class="form-group">';
				html += ' <label for="formSetting-suffix">后缀</label>';
				html += ' <input type="text" class="form-control" id="formSetting-suffix">';
				html += '</div>';
				return html;
			},
			"initValue": function(val) {
				if(val) {
					$("#formSetting-suffix").val(val);
				}
			},
			"bindEvent": function(elementInstance) {
				$("#formSetting-suffix").on("input", function() {
					let val = $(this).val();
					elementInstance.suffix(val);
				});
			},
			"render": function(parent, elementInstance) {
				let inputItem;
				parent.append(this.templete());
				this.initValue(elementInstance.suffix());
				this.bindEvent(elementInstance);
			}
		}
	}
	
	let helperText = {
		"helperText": {
			"name": "提示文本",
			"templete": function() {
				let html = '';
				html += '<div class="form-group">';
				html += ' <label for="formSetting-helperText">提示文本</label>';
				html += ' <textarea id="formSetting-helperText" class="form-control" rows="2"></textarea>';
				html += '</div>';
				return html;
			},
			"initValue": function(val) {
				$("#formSetting-helperText").val(val);
			},
			"bindEvent": function(elementInstance) {
				$("#formSetting-helperText").on("input", function() {
					let val = $(this).val();
					elementInstance.helperText(val);
				});
			},
			"render": function(parent, elementInstance) {
				parent.append(this.templete());
				this.initValue(elementInstance.helperText());
				this.bindEvent(elementInstance);
			}
		}
	}
	
	let helperTextColor = {
		"helperTextColor": {
			"name": "提示文本颜色",
			"render": function(parent, elementInstance) {
				
			}
		}
	}
	
	
	let validate = {
		"validate": {
			"name": "校验",
			"templete": function() {
				let html = '';
				html += '<div class="form-group">';
				html += ' <label for="formSetting-validateRule">校验规则</label>';
				html += ' <select class="form-control" id="formSetting-validateRule">';
				html += '  <option value="">无</option>';
				//formValidator中定义的验证内容
				{
					html += '  <option value="telephone">座机号</option>';
					html += '  <option value="mobilephone">手机号</option>';
					html += '  <option value="email">邮箱</option>';
					html += '  <option value="ip">IP</option>';
					html += '  <option value="chinese">中文</option>';
					html += '  <option value="url">网址</option>';
					html += '  <option value="zipcode">邮编</option>';
					html += '  <option value="onlyNumber">数字</option>';
					html += '  <option value="onlyLetter">字母</option>';
					html += '  <option value="macAdd">MAC地址</option>';
				}
				html += ' </select>';
				html += '</div>';
				
				html += '<div class="form-group">';
				html += ' <label for="formSetting-validateReg">自定义正则</label>';
				html += ' <input type="text" class="form-control" id="formSetting-validateReg">';
				html += '</div>';
				
				html += '<div class="form-group">';
				html += ' <label for="formSetting-validateRegTitle">自定义正则提示</label>';
				html += ' <input type="text" class="form-control" id="formSetting-validateRegTitle">';
				html += '</div>';
				
				return html;
			},
			"initValue": function(conf) {
				if(conf) {
					$("#formSetting-validateRule").val(conf.rule || "");
					$("#formSetting-validateReg").val(conf.reg || "");
					$("#formSetting-validateRegTitle").val(conf.regtitle || "");
				}
			},
			"bindEvent": function(elementInstance) {
				$("#formSetting-validateRule").on("change", function() {
					let val = $(this).val();
					let conf = elementInstance.validateConfig();
					conf.rule = val;
					elementInstance.validateConfig(conf);
				});
				$("#formSetting-validateReg").on("input", function() {
					let val = $(this).val();
					let conf = elementInstance.validateConfig();
					conf.reg = val;
					elementInstance.validateConfig(conf);
				});
				$("#formSetting-validateRegTitle").on("input", function() {
					let val = $(this).val();
					let conf = elementInstance.validateConfig();
					conf.regtitle = val;
					elementInstance.validateConfig(conf);
				});
			},
			"render": function(parent, elementInstance) {
				parent.append(this.templete());
				this.initValue(elementInstance.validateConfig());
				this.bindEvent(elementInstance);
			}
		}
	}
	
	let inputLength = {
		"inputLength": {
			"name": "输入长度限制",
			"templete": function() {
				let html = '';
				html += '<div class="form-group">';
				html += ' <label for="formSetting-limit-min">长度限制</label>';
				html += ' <div class="input-group">';
				html += ' <span class="input-group-addon">最短</span>';
				html += ' <input type="number" class="form-control" id="formSetting-limit-min" min=0>';
				html += ' </div>';
				html += ' <div class="input-group">';
				html += ' <span class="input-group-addon">最长</span>';
				html += ' <input type="number" class="form-control" id="formSetting-limit-max" min=1>';
				html += ' </div>';
				html += '</div>';
				return html;
			},
			"initValue": function(conf) {
				if(conf) {
					$("#formSetting-limit-min").val(conf.minlength || "");
					$("#formSetting-limit-max").val(conf.maxlength || "");
				}
			},
			"bindEvent": function(elementInstance) {
				$("#formSetting-limit-min").on("input", function() {
					let val = $(this).val();
					let conf = elementInstance.validateConfig();
					conf.minlength = val;
					elementInstance.validateConfig(conf);
				});
				$("#formSetting-limit-max").on("input", function() {
					let val = $(this).val();
					let propertyLength = elementInstance.property?.propertyLength;
					if(val && propertyLength && val > propertyLength) {
						$(this).val(propertyLength);
						return false;
					}
					let conf = elementInstance.validateConfig();
					conf.maxlength = val;
					elementInstance.validateConfig(conf);
				});
			},
			"render": function(parent, elementInstance) {
				parent.append(this.templete());
				this.initValue(elementInstance.validateConfig());
				this.bindEvent(elementInstance);
				{
					// 最大长度不能超过模型属性长度
					let propertyLength = elementInstance.property?.propertyLength;
					if(propertyLength > 1) {
						$("#formSetting-limit-max").attr({"max": propertyLength, "title": "最大长度为"+propertyLength});
					}
				}
			}
		}
	}
	
	let bind2ModelProperty = {
		"bind2ModelProperty": {
			"name": "绑定到模型字段",
			"templete": function() {
				let html = '';
				html += '<div class="form-group">';
				html += ' <label for="formSetting-bind-model-property">绑定模型字段</label>';
				html += ' <select class="form-control" id="formSetting-bind-model-property">';
				html += ' </select>';
				html += '</div>';
				return html;
			},
			"loadOptions": function() {
				let html = '<option value="">请选择</option>';
				formElementManager.iteratorModelProperty(function(property){
					if(!property.__shown) {
						html += '<option value="' + property.id + '">' + property.propertyName + '</option>';
					}
				});
				$("#formSetting-bind-model-property").html(html);
			},
			"bindEvent": function(elementInstance) {
				$("#formSetting-bind-model-property").on("change", function() {
					let val = $(this).val();
					elementInstance.propertyId = val;
					let property = formElementManager.getModelProperty(val);
					if(property) {
						elementInstance.property = property;
						elementInstance.label(property.propertyName);
						elementInstance.shown(true);
					}
				});
			},
			"render": function(parent, elementInstance) {
				let propertyId = elementInstance.propertyId;
				if(propertyId) {
					return;//模型字段不能绑定
				}
				parent.append(this.templete());
				this.loadOptions();
				this.bindEvent(elementInstance);
			}
		}
	}
	
	
	let formEvent = {
		"formEvent": {
			"name": "事件",
			"hide": function() {
				let li = this.getDomLi();
				if(li.length) {
					li.hide().prev().hide();
				}
			},
			"getDomLi": function() {
				return $("#form-event-setting");
			},
			"openModel": function() {
				let html = '';
				html += '<div class="form-group">';
				html += ' <label for="formSetting-eventName"><span class="required-star">*</span>事件名称</label>';
				html += ' <div class="select-input-wrap">';
				html += ' <select class="form-control" onchange="this.nextElementSibling.value=this.value;">';
				html += '<option value=""></option>';
				html += '<option value="click">click</option>';
				html += '<option value="input">input</option>';
				html += '<option value="change">change</option>';
				html += '<option value="focus">focus</option>';
				html += '<option value="blur">blur</option>';
				html += '<option value="keydown">keydown</option>';
				html += ' </select>';
				html += ' <input type="text" id="formSetting-eventName" class="form-control" data-original-title="事件名称不能为空">';
				html == ' </div>';
				html += '</div>';
				
				html += '<div class="form-group">';
				html += ' <label for="formSetting-eventContent"><span class="required-star">*</span>内容</label>';
				html += ' <textarea rows="5" id="formSetting-eventContent" class="form-control"></textarea>';
				html += '</div>';
				
				let modalWin = commonUtil.modal.open(html, "编辑事件");
				this.loadOptions();
				return modalWin;
			},
			"loadOptions": function() {
				//TODO
				//将已定义的事件名称设置为不可选
			},
			/**
			 * 将事件添加到面板中
			 */
			"addEvent2Panel": function(eventName, eventContent, tmpInstance) {
				let li = this.getDomLi();
				let tmpId = "eventwrap-" + eventName;
				let wrap = $( "#" + tmpId );
				if(!wrap.length) {
					wrap = $('<div id="' + tmpId + '" class="form-group event-wrap" data-eventName="' + eventName + '"></div>');
					li.append(wrap);
				}
				let html = '';
				html += ' <label></label>';
				html += ' <pre></pre>';
				wrap.html(html);
				wrap.find('label').text(eventName);
				wrap.find('pre').text(eventContent);
				
				let btnHtml = '';
				btnHtml += '<span class="btn-wrapper">';
				btnHtml += ' <span title="编辑" class="btn-edit edit"><i class="glyphicon glyphicon-edit"></i></span>';
				btnHtml += ' <span title="删除" class="btn-remove remove"><i class="glyphicon glyphicon-trash"></i></span>';
				btnHtml += '</span>';
				wrap.prepend(btnHtml);
				wrap.data('connectDomIns', tmpInstance);
			},
			"bindEvent": function(modalWin, tmpInstance, editEventName) {
				let ghost = this;
				modalWin.find(".btn-save").off("click").on("click", function(evt) {
					let eventName = $("#formSetting-eventName").val();
					let eventContent = $("#formSetting-eventContent").val();
					if(eventName && eventContent) {
						{
							//事件名称改了，要删除之前的事件名称，添加新的事件
							if(eventName !== editEventName) {
								ghost.removeEvent(editEventName, tmpInstance);
							}
						}
						let eventObj = {};
						eventObj[eventName] = eventContent;
						tmpInstance.events(eventObj);
						ghost.addEvent2Panel(eventName, eventContent, tmpInstance);
						modalWin.modal('hide');
						return true;
					} else {
						commonUtil.modal.warn("事件名称和事件内容不能为空");
						return false;
					}
				});
			},
			/**
			 * 编辑自定义事件
			 */
			"editEvent": function(eventName, eventContent, tmpInstance) {
				let modalWin = this.openModel();
				$("#formSetting-eventName").val(eventName);
				$("#formSetting-eventContent").val(eventContent);
				this.bindEvent(modalWin, tmpInstance, eventName);
			},
			/**
			 * 删除自定义事件
			 */
			"removeEvent": function(eventName, tmpInstance) {
				tmpInstance.removeEvent(eventName);
				let tmpId = "eventwrap-" + eventName;
				$( "#" + tmpId ).remove();
			},
			/**
			 * 初始化显示之前定义的事件
			 */
			"initShow": function(tmpInstance) {
				$("#form-event-setting .event-wrap").remove();
				let eventObj = tmpInstance.events();
				if(typeof eventObj === "object") {
					for(let eventName in eventObj) {
						this.addEvent2Panel(eventName, eventObj[eventName], tmpInstance);
					}
				}
			},
			"render": function(activeElement, tmpInstance) {
				let li = this.getDomLi();
				if(!li.length) {
					return false;
				}
				li.show().prev().show();
				let ghost = this;
				
				{
					// 初始化显示之前定义的事件
					this.initShow(tmpInstance);
				}
				li.find("button").off("click").on("click", function(evt) {
					//点击按钮“添加事件”
					//打开事件定义模态框
					let modalWin = ghost.openModel();
					//绑定保存按钮事件
					ghost.bindEvent(modalWin, tmpInstance);
				});
			}
		}
	}
	
	
	/**
	 * 表单全局配置
	 */
	let formConfig = {
		"formConfig": {
			"name": "表单全局配置",
			"getConfig": function() {
				return {
					"postAddress": $("#formConfig-postAddress").val(),
					"dataAddress": $("#formConfig-dataAddress").val()
				}
			},
			"render": function() {
				$("#form-config-modal").modal();
			}
		}
	}
	//定义设置项
	let settingItems = {
		formConfig,
		formEvent,
		labelName,
		formWidth, 
		requireAndReadonly, 
		defaultValue, 
		prefix, 
		suffix,
		helperText, 
		helperTextColor,
		validate, 
		inputLength,
		bind2ModelProperty
	};

	//主对象
	let formSetting = {};

	formSetting.renderPanel = _001_renderPanel;//表单项设置面板
	
	formSetting.renderLayoutSettingPanel = _002_renderLayoutSettingPanel;//布局设置面板
	
	{
		//将设置项拷贝到主对象上
		for(let k in settingItems) {
			formSetting[k] = settingItems[k][k];
		}
	}


	return formSetting;
});
